//我的资产页面内容（报错）原因：datasource必须获取为数组
import React, { useState, useEffect } from 'react';
import { Card, Space,Statistic,Cascader, InputNumber, Select,Button,Modal ,message,Table, Col, Row ,Pagination, Drawer} from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import axios from 'axios';
import { Link, useRouter } from 'next/router';
import { PieChart} from 'recharts';
import MyChart from './pieChart';

const Assets = () => {
  const router = useRouter();
  //资产信息
  const [totalAsset, setTotalAsset] = useState(0);
  const [totalProfit, setTotalProfit] = useState(0);
  const [yesterdayProfit, setYesterdayProfit] = useState(0);
  const [totalProfitRate, setTotalProfitRate] = useState(0);
  const [tradeRecords, setTradeRecords] = useState([]);
  const [holdStocks, setHoldStocks] = useState([]);
  const [cash, setCash] = useState([]);
  const [stockValue, setStockValue] = useState(0);
  const [holdStocksValue, setHoldStocksValue] = useState([]);
  const [optionalStocks, setOptionalStocks,]= useState([]);
  //交易记录表格
  const columns_record = [
    {
      title: '交易时间',
      dataIndex: 'trade_time',
      key: 'trade_time',
    },
    {
      title: '交易类型',
      dataIndex: 'trade_type',
      key: 'trade_type',
    },
    {
      title: '股票代码',
      dataIndex: 'stock_code',
      key:'stock_code',
    },
    {
      title: '股票名称',
      dataIndex: 'stock_name',
      key:'stock_name',
    },
    {
      title: '股票价格',
      dataIndex: 'stock_price',
      key:'stock_price',
    },
    {
      title: '股票数量',
      dataIndex: 'stock_amount',
      key:'stock_amount',
    },
    {
      title: '总价',
      dataIndex: 'total_price',
      key: 'total_price',
    },
    {
      title: '是否手动交易',
      dataIndex: 'is_manual',
      key: 'is_manual',
      render: (text, record) => (
        <span>{text ? '✓' : '✗'}</span>
      ),
    },
    {
      title: '备注',
      dataIndex: 'notes',
      key: 'notes',
    },
  ];
  
  //持仓股票表格
  const columns_hold = [
    {
      title: '股票代码',
      dataIndex: 'code',
      key:'code',
    },
    {
      title: '股票名称',
      dataIndex: 'name',
      key:'name',
    },
    {
      title: '股票价格',
      dataIndex: 'price',
      key:'price',
    },
    {
      title: '股票数量',
      dataIndex: 'amount',
      key:'amount',
    },
    {
      title: '总价格',
      dataIndex: 'total_price',
      key:'total_price',
    },
    
  ];

  //自选股票表格
  const columns_optional = [
    {
      title: '股票代码',
      dataIndex: 'code',
      key:'code',
    },
    {
      title: '股票名称',
      dataIndex: 'name',
      key:'name',
    },
    
  ];
//持仓股票与自选股票
  const tabList = [
    {
      key: 'tab1',
      tab: '持仓股票',
    },
    {
      key: 'tab2',
      tab: '自选股票',
    },
  ];
  const contentList = {
    tab1: <Table columns={columns_hold} dataSource={holdStocks} scroll={{y:120}} pagination={ false}/>,
    tab2: <Table columns={columns_optional} dataSource={optionalStocks} scroll={{y:120}} pagination={ false}/>,
  };
  const [activeTabKey1, setActiveTabKey1] = useState('tab1');
  const onTab1Change = (key) => {
    setActiveTabKey1(key);
  };
  
  
  //获取交易记录
  useEffect(() => {
    const fetchTradeRecords = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/user/trade_record', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        console.log("获得的数据是:", response.data.data);
        setTradeRecords(response.data.data);
      } catch (error) {
        console.log('Error:', error);
        // 登录失败时的处理
        if (error.response) {
          // 服务器返回了错误响应
          const errorMessage = error.response.data.msg || '信息获取失败';
          message.error(errorMessage);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          message.error('请求失败，请检查网络连接');
        } else {
          // 发送请求时出了问题
          message.error('请求失败，请检查后端服务是否可用');
        }
      }
    };
    fetchTradeRecords();
  }, []);

  //获取用户资产
  useEffect(() => {
    const fetchData = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/user/wealth_info', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        console.log("获得的数据是:", response.data.data);
        const data = response.data.data;
        setCash(data.cash);
        setTotalAsset(data.total_asset);
        setTotalProfit(data.total_profit);
        setYesterdayProfit(data.yesterday_profit);
        setTotalProfitRate(data.total_profit_rate);
        setHoldStocks(data.hold_stock.data);
        setOptionalStocks(data.optional_stock.data);
        setStockValue(data.stock_value);
      } catch (error) {
        console.log('Error:', error);
        // 登录失败时的处理
        if (error.response) {
          // 服务器返回了错误响应
          const errorMessage = error.response.data.msg || '信息获取失败';
          message.error(errorMessage);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          message.error('请求失败，请检查网络连接');
        } else {
          // 发送请求时出了问题
          message.error('请求失败，请检查后端服务是否可用');
        }
      }
    };
    fetchData();
  }, []);

  

  const [open, setOpen] = useState(false);
  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };

return (
    <Space direction="vertical" size={16}>
  <Space direction="horizontal" size={16}>
    <Card
      title="我的资产"
      style={{
        width: 500,
        height: 310,
      }}
      scroll={{y:50}}
    >
      <div>
      <Row gutter={16}>
        <Col span={12}>
          <Statistic title="总资产(RMB)" value={totalAsset} />
          <Statistic title="浮动盈亏(RMB)" value={totalProfit} />
          <Statistic title="昨日盈亏(RMB)" value={yesterdayProfit} />
        </Col>
        <Col span={12}>
          <Statistic title="总盈亏率(%)" value={totalProfitRate} />
          <Statistic title="现金(RMB)" value={cash} />
          <Statistic title="股票市值(RMB)" value={stockValue} />
        </Col>
        <Button type="link" onClick={showDrawer}>
       查看资产配置图
      </Button>
      <Drawer title="我的资产配置图" onClose={onClose} open={open} width={500}>
        <MyChart />
       
      </Drawer>
      </Row>
    </div>
    </Card>

    <Card     
      title="股票信息"
      style={{
        width: 640,
        height: 310,
      }}
      tabList={tabList}
        activeTabKey={activeTabKey1}
        onTabChange={onTab1Change}
    >
       {contentList[activeTabKey1]}
    </Card>
    </Space>
    <Card  
      title="交易记录"
      style={{
        width: 1150,
        height: 350,
      }}
    >
      <Table columns={columns_record} dataSource={tradeRecords} pagination={{ pageSize: 2 }} />  
      
      
    </Card>
  </Space>
)
};
export default Assets;